package cn.com.cvit.nc.util;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * 图片上传
 * */
public class FileUpload {
	public static String uploadFile(MultipartFile file, HttpServletRequest request, String photo) throws IOException {
        String photos = photo;
		String fileName = file.getOriginalFilename();
        String img_path = "Subscribe_mig/";
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmm");//时间格式
        String date=format.format(new Date());//获取当前时间
        String dir = request.getSession().getServletContext().getRealPath("/");//总路径
        String img_name = date+Utils.createRandString();//新生成的图片名（当前时间+六位生成码）
        StringBuilder path = new StringBuilder(dir.substring(0, dir.indexOf("Subscribe")) + img_path);
        StringBuilder delete = new StringBuilder(dir.substring(0, dir.indexOf("Subscribe")));//服务器weapps路径
        String photopath = delete+ photos;//需要删除的路径
        if(photos!=null){
        	deleteServerFile(photopath);
        }
        File tempFile = new File(path.toString(),String.valueOf(img_name+".png"));
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdir();
        }
        if (!tempFile.exists()) {
            tempFile.createNewFile();
        }
        file.transferTo(tempFile);
        return img_path + img_name+".png";
    }
	
	
	/**
	 * 删除服务器文件
	 * */
	public static boolean deleteServerFile(String imgpath){
		boolean delete_flag = false;
		String b=imgpath.replace("\\","/");
		File file = new File(b);
		if (file.exists() && file.isFile() && file.delete())
	        delete_flag = true;
	       else
	        delete_flag = false;
	    return delete_flag;
	}
	
	
	/*public String uploadNews(String tid, String sid) {
		System.out.println("BaseAction-转换后路径"+temp_path);
		String img = null;
		try {
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//子文件夹.
			String img_path = "/tid_"+tid+"/sid_"+sid+"/News/";
			String dir = getServletContext().getRealPath("/");//总路径
			StringBuilder path = new StringBuilder(dir.substring(0, dir.indexOf("app_agent")) + "app_agent_IMG" + img_path);
			if (!Utils.isNull(uoload_Obj)) {
				String img_name = Utils.getUUID() + ".jpg";//图片名字
				Utils.upload(uoload_Obj.getFile(), path.toString(), img_name);
				img= img_path + img_name;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//System.out.println("shop_img:"+shop_img);
		return img;
	}*/
	
}